package com.hrh.selectsystem.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hrh.selectsystem.common.ErrorCode;
import com.hrh.selectsystem.exception.BusinessException;
import com.hrh.selectsystem.mapper.ChoiceRecordMapper;
import com.hrh.selectsystem.mapper.MentorMapper;
import com.hrh.selectsystem.mapper.StudentMapper;
import com.hrh.selectsystem.model.dto.choicerecord.ChoiceRecordAddRequest;
import com.hrh.selectsystem.model.dto.choicerecord.ChoiceRecordQueryRequest;
import com.hrh.selectsystem.model.dto.mentor.MentorQueryRequest;
import com.hrh.selectsystem.model.entity.ChoiceRecord;
import com.hrh.selectsystem.model.entity.Mentor;
import com.hrh.selectsystem.model.entity.Student;
import com.hrh.selectsystem.model.vo.choiceRecord.ChoiceRecordQueryMentorVO;
import com.hrh.selectsystem.model.vo.choiceRecord.ChoiceRecordQueryVO;
import com.hrh.selectsystem.model.vo.choiceRecord.ChoiceRecordVO;
import com.hrh.selectsystem.service.ChoiceRecordService;
import com.hrh.selectsystem.service.MentorApplicationCountService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
* @author hetongxue
* @description 针对表【choice_record(选择记录)】的数据库操作Service实现
* @createDate 2024-10-26 14:03:03
*/
@Service
public class ChoiceRecordServiceImpl extends ServiceImpl<ChoiceRecordMapper, ChoiceRecord>
    implements ChoiceRecordService{
    
    @Resource
    private StudentMapper studentMapper;
    @Resource
    private ChoiceRecordMapper choiceRecordMapper;
    @Resource
    private MentorMapper mentorMapper;
    @Resource
    private MentorApplicationCountService mentorApplicationCountService;

    /**
     * 提交选择
     * @param studentId
     * @param choiceRecordAddRequest
     */
    @Override
    public boolean submitChoices(ChoiceRecordAddRequest choiceRecordAddRequest, Long studentId) {
        // 验证学生是否存在
        Student student = studentMapper.selectById(studentId);
        if (student == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "学生不存在");
        }

        // 验证导师是否存在
        Mentor firstChoice = mentorMapper.selectById(choiceRecordAddRequest.getFirstchoice());
        if (firstChoice == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "第一志愿导师不存在");
        }

        Mentor secondChoice = mentorMapper.selectById(choiceRecordAddRequest.getSecondchoice());
        if (secondChoice == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "第二志愿导师不存在");
        }

        Mentor thirdChoice = mentorMapper.selectById(choiceRecordAddRequest.getThirdchoice());
        if (thirdChoice == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "第三志愿导师不存在");
        }

        // 检查学生是否已经提交过志愿
        QueryWrapper<ChoiceRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("studentid", studentId);
        ChoiceRecord record = choiceRecordMapper.selectOne(queryWrapper);
        if (record != null) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "学生已提交志愿");
        }

        //取出导师id
        Long firstMentorId = choiceRecordAddRequest.getFirstchoice();
        Long secondMentorId = choiceRecordAddRequest.getSecondchoice();
        Long thirdMentorId = choiceRecordAddRequest.getThirdchoice();

        //导师申请数+1
        mentorApplicationCountService.updateMentorApplicationCount(firstMentorId);
        mentorApplicationCountService.updateMentorApplicationCount(secondMentorId);
        mentorApplicationCountService.updateMentorApplicationCount(thirdMentorId);

        // 保存选择记录
        ChoiceRecord choiceRecord = new ChoiceRecord();
        BeanUtils.copyProperties(choiceRecordAddRequest, choiceRecord);
        choiceRecord.setStudentid(studentId);
        choiceRecordMapper.insert(choiceRecord);

        return true;
    }

    /**
     * 通过学生id查询选择记录
     * @param studentId
     * @return
     */
    @Override
    public Wrapper<ChoiceRecord> getQueryWrapperById(Long studentId) {
        if (studentId == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数为空");
        }
        return new QueryWrapper<ChoiceRecord>().eq("studentid", studentId);
    }

    /**
     * 通过学生id查询学生志愿导师
     * @param studentId
     * @return
     */
    @Override
    public ChoiceRecordQueryMentorVO getStudentMentorChoices(Long studentId) {
        ChoiceRecord choiceRecord = choiceRecordMapper.getChoiceRecordByStudentId(studentId);
        if (choiceRecord == null) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "学生未提交志愿");
        }

        List<Long> mentorIds = new ArrayList<>();
        if (choiceRecord.getFirstchoice() != null) {
            mentorIds.add(choiceRecord.getFirstchoice());
        }
        if (choiceRecord.getSecondchoice() != null) {
            mentorIds.add(choiceRecord.getSecondchoice());
        }
        if (choiceRecord.getThirdchoice() != null) {
            mentorIds.add(choiceRecord.getThirdchoice());
        }

        List<MentorQueryRequest> mentors = choiceRecordMapper.getMentorsByIds(mentorIds);

        ChoiceRecordQueryMentorVO choiceRecordQueryMentorVO = new ChoiceRecordQueryMentorVO();
        choiceRecordQueryMentorVO.setStudentid(studentId);
        choiceRecordQueryMentorVO.setMentors(mentors);
        choiceRecordQueryMentorVO.setFirstchoice(choiceRecord.getFirstchoice());
        choiceRecordQueryMentorVO.setSecondchoice(choiceRecord.getSecondchoice());
        choiceRecordQueryMentorVO.setThirdchoice(choiceRecord.getThirdchoice());
        choiceRecordQueryMentorVO.setFirststatus(choiceRecord.getFirststatus());
        choiceRecordQueryMentorVO.setSecondstatus(choiceRecord.getSecondstatus());
        choiceRecordQueryMentorVO.setThirdstatus(choiceRecord.getThirdstatus());

        return choiceRecordQueryMentorVO;
    }

    /**
     * 分页获取学生申请记录(管理员)
     * @param current
     * @param size
     * @return
     */
    @Override
    public Page<ChoiceRecordQueryVO> listSubmitChoicesByPage(ChoiceRecordQueryRequest choiceRecordQueryRequest, long current, long size) {
        // region
//        //取出轮次
//        Integer round = choiceRecordQueryRequest.getRound();
//
//        //构造查询条件
//        QueryWrapper<ChoiceRecord> queryWrapper = addQueryConditions(choiceRecordQueryRequest);
//        List<ChoiceRecord> choiceRecordList = choiceRecordMapper.selectList(queryWrapper);
//
//        // 将查询结果转换为ChoiceRecordQueryVO列表
//        List<ChoiceRecordQueryVO> choiceRecordQueryVOList = choiceRecordList.stream()
//                .flatMap(choiceRecord -> {
//                    // 分别取出学生id，第一志愿老师id，第二志愿老师id，第三志愿老师id，第一志愿状态，第二志愿状态，第三志愿状态
//                    Long studentId = choiceRecord.getStudentid();
//                    Long firstChoice = choiceRecord.getFirstchoice();
//                    Long secondChoice = choiceRecord.getSecondchoice();
//                    Long thirdChoice = choiceRecord.getThirdchoice();
//                    String firstStatus = choiceRecord.getFirststatus();
//                    String secondStatus = choiceRecord.getSecondstatus();
//                    String thirdStatus = choiceRecord.getThirdstatus();
//
//                    // 通过学生id查询学生学号、名字
//                    Student student = studentMapper.selectById(studentId);
//                    String studentAccount = student.getStudentaccount();
//                    String studentName = student.getStudentname();
//
//                    // 通过导师id查询导师工号、名字
//                    Mentor firstMentor = mentorMapper.selectById(firstChoice);
//                    String firstMentorAccount = firstMentor.getMentoraccount();
//                    String firstMentorName = firstMentor.getMentorname();
//
//                    Mentor secondMentor = mentorMapper.selectById(secondChoice);
//                    String secondMentorAccount = secondMentor.getMentoraccount();
//                    String secondMentorName = secondMentor.getMentorname();
//
//                    Mentor thirdMentor = mentorMapper.selectById(thirdChoice);
//                    String thirdMentorAccount = thirdMentor.getMentoraccount();
//                    String thirdMentorName = thirdMentor.getMentorname();
//
//                    // 根据轮次返回不同的志愿信息
//                    List<ChoiceRecordQueryVO> vos = new ArrayList<>();
//                    if (round == null || round == 1) {
//                        // 设置第一志愿信息
//                        ChoiceRecordQueryVO vo = new ChoiceRecordQueryVO();
//                        vo.setId(choiceRecord.getId());
//                        vo.setStudentaccount(studentAccount);
//                        vo.setStudentname(studentName);
//                        vo.setMentoraccount(firstMentorAccount);
//                        vo.setMentorname(firstMentorName);
//                        vo.setRound(1);
//                        vo.setStatus(firstStatus);
//                        vos.add(vo);
//                    }
//
//                    if (round == null || round == 2) {
//                        // 设置第二志愿信息
//                        ChoiceRecordQueryVO vo2 = new ChoiceRecordQueryVO();
//                        vo2.setId(choiceRecord.getId());
//                        vo2.setStudentaccount(studentAccount);
//                        vo2.setStudentname(studentName);
//                        vo2.setMentoraccount(secondMentorAccount);
//                        vo2.setMentorname(secondMentorName);
//                        vo2.setRound(2);
//                        vo2.setStatus(secondStatus);
//                        vos.add(vo2);
//                    }
//
//                    if (round == null || round == 3) {
//                        // 设置第三志愿信息
//                        ChoiceRecordQueryVO vo3 = new ChoiceRecordQueryVO();
//                        vo3.setId(choiceRecord.getId());
//                        vo3.setStudentaccount(studentAccount);
//                        vo3.setStudentname(studentName);
//                        vo3.setMentoraccount(thirdMentorAccount);
//                        vo3.setMentorname(thirdMentorName);
//                        vo3.setRound(3);
//                        vo3.setStatus(thirdStatus);
//                        vos.add(vo3);
//                    }
//                    return vos.stream();
//                })
//                .collect(Collectors.toList());
//
//        // 创建分页结果对象
//        Page<ChoiceRecordQueryVO> choiceRecordQueryVOPage = new Page<>(current, size);
//        choiceRecordQueryVOPage.setRecords(choiceRecordQueryVOList);
//        choiceRecordQueryVOPage.setTotal(choiceRecordQueryVOList.size());
//        return choiceRecordQueryVOPage;
        //endregion
        // 取出轮次
        Integer round = choiceRecordQueryRequest.getRound();

        // 构造查询条件
        QueryWrapper<ChoiceRecord> queryWrapper = addQueryConditions(choiceRecordQueryRequest);

        if (size > 3){
            size = size/3;
        }
        // 使用 Page 对象进行分页查询
        Page<ChoiceRecord> page = Page.of(current, size);
        Page<ChoiceRecord> choiceRecordPage = choiceRecordMapper.selectPage(page, queryWrapper);

        // 将查询结果转换为 ChoiceRecordQueryVO 列表
        List<ChoiceRecordQueryVO> choiceRecordQueryVOList = choiceRecordPage.getRecords().stream()
                .flatMap(choiceRecord -> {
                    // 分别取出学生id，第一志愿老师id，第二志愿老师id，第三志愿老师id，第一志愿状态，第二志愿状态，第三志愿状态
                    Long studentId = choiceRecord.getStudentid();
                    Long firstChoice = choiceRecord.getFirstchoice();
                    Long secondChoice = choiceRecord.getSecondchoice();
                    Long thirdChoice = choiceRecord.getThirdchoice();
                    String firstStatus = choiceRecord.getFirststatus();
                    String secondStatus = choiceRecord.getSecondstatus();
                    String thirdStatus = choiceRecord.getThirdstatus();

                    // 通过学生id查询学生学号、名字
                    Student student = studentMapper.selectById(studentId);
                    String studentAccount = student.getStudentaccount();
                    String studentName = student.getStudentname();

                    // 通过导师id查询导师工号、名字
                    Mentor firstMentor = mentorMapper.selectById(firstChoice);
                    String firstMentorAccount = firstMentor.getMentoraccount();
                    String firstMentorName = firstMentor.getMentorname();

                    Mentor secondMentor = mentorMapper.selectById(secondChoice);
                    String secondMentorAccount = secondMentor.getMentoraccount();
                    String secondMentorName = secondMentor.getMentorname();

                    Mentor thirdMentor = mentorMapper.selectById(thirdChoice);
                    String thirdMentorAccount = thirdMentor.getMentoraccount();
                    String thirdMentorName = thirdMentor.getMentorname();

                    // 根据轮次返回不同的志愿信息
                    List<ChoiceRecordQueryVO> vos = new ArrayList<>();
                    if (round == null || round == 1) {
                        // 设置第一志愿信息
                        ChoiceRecordQueryVO vo = new ChoiceRecordQueryVO();
                        vo.setId(choiceRecord.getId());
                        vo.setStudentaccount(studentAccount);
                        vo.setStudentname(studentName);
                        vo.setMentoraccount(firstMentorAccount);
                        vo.setMentorname(firstMentorName);
                        vo.setRound(1);
                        vo.setStatus(firstStatus);
                        vos.add(vo);
                    }

                    if (round == null || round == 2) {
                        // 设置第二志愿信息
                        ChoiceRecordQueryVO vo2 = new ChoiceRecordQueryVO();
                        vo2.setId(choiceRecord.getId());
                        vo2.setStudentaccount(studentAccount);
                        vo2.setStudentname(studentName);
                        vo2.setMentoraccount(secondMentorAccount);
                        vo2.setMentorname(secondMentorName);
                        vo2.setRound(2);
                        vo2.setStatus(secondStatus);
                        vos.add(vo2);
                    }

                    if (round == null || round == 3) {
                        // 设置第三志愿信息
                        ChoiceRecordQueryVO vo3 = new ChoiceRecordQueryVO();
                        vo3.setId(choiceRecord.getId());
                        vo3.setStudentaccount(studentAccount);
                        vo3.setStudentname(studentName);
                        vo3.setMentoraccount(thirdMentorAccount);
                        vo3.setMentorname(thirdMentorName);
                        vo3.setRound(3);
                        vo3.setStatus(thirdStatus);
                        vos.add(vo3);
                    }
                    return vos.stream();
                })
                .collect(Collectors.toList());

        // 创建分页结果对象
        Page<ChoiceRecordQueryVO> choiceRecordQueryVOPage = new Page<>(current, size);
        choiceRecordQueryVOPage.setRecords(choiceRecordQueryVOList);
        choiceRecordQueryVOPage.setTotal(choiceRecordPage.getTotal() * 3);
        return choiceRecordQueryVOPage;

    }

    /**
     * 获取学生已选导师id
     * @param studentId
     * @return
     */
    @Override
    public ChoiceRecordVO getChoiceRecordsByStudentId(Long studentId) {
        ChoiceRecord choiceRecord = choiceRecordMapper.selectOne(getQueryWrapperById(studentId));
        ChoiceRecordVO choiceRecordVO = new ChoiceRecordVO();
        choiceRecordVO.setStudentid(choiceRecord.getStudentid());
        choiceRecordVO.setFirstchoice(choiceRecord.getFirstchoice());
        choiceRecordVO.setSecondchoice(choiceRecord.getSecondchoice());
        choiceRecordVO.setThirdchoice(choiceRecord.getThirdchoice());
        return choiceRecordVO;
    }

    /**
     * 添加查询条件
     * @param choiceRecordQueryRequest
     */
    private QueryWrapper<ChoiceRecord> addQueryConditions(ChoiceRecordQueryRequest choiceRecordQueryRequest) {
        QueryWrapper<ChoiceRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("studentid", "firstchoice", "secondchoice", "thirdchoice", "firststatus", "secondstatus", "thirdstatus");

        String studentaccount = choiceRecordQueryRequest.getStudentaccount();
        String studentname = choiceRecordQueryRequest.getStudentname();
        String mentoraccount = choiceRecordQueryRequest.getMentoraccount();
        Integer round = choiceRecordQueryRequest.getRound();

        if (StringUtils.isNotBlank(studentaccount)) {
            Long studentId = studentMapper.selectIdByAccount(studentaccount);
            queryWrapper.eq(studentId != null, "studentid", studentId);
        }

        if (StringUtils.isNotBlank(studentname)) {
            Long studentId = studentMapper.selectIdByName(studentname);
            queryWrapper.eq(studentId != null, "studentid", studentId);
        }

        // 处理导师账号查询条件
        if (StringUtils.isNotBlank(mentoraccount)) {
            Long mentorId = mentorMapper.selectIdByAccount(mentoraccount);
            queryWrapper.eq(mentorId != null, "firstchoice", mentorId)
                    .or()
                    .eq(mentorId != null, "secondchoice", mentorId)
                    .or()
                    .eq(mentorId != null, "thirdchoice", mentorId);
        }

        return queryWrapper;
    }
}




